package JAVA300.第十一章多线程;

/**
 * 实例练习同步问题1
 * 电影院抢票--仅考虑数量
 */
public class thread_16_synchronized_exp1 {
    public static void main(String[] args) {
        Ciname ciname = new Ciname(2,"CGV");
        new Thread(new Customs(ciname,2),"hqq").start();
        new Thread(new Customs(ciname,1),"qyh").start();

    }
}

class Ciname {
    int available;//可选座位数目
    String name ;//影院

    public Ciname(int available, String name) {
        this.available = available;
        this.name = name;
    }

    public boolean bookTickets(int wantSeats){
        if (wantSeats>available){
            return false;
        }else {
            System.out.println("可选座位数目："+available);
            available -= wantSeats;
            //System.out.println("您成功预订座位数目："+wantSeats);
            return true;


        }
    }
}

class Customs implements Runnable{

    Ciname ciname;
    int tickets;

    public Customs(Ciname ciname, int tickets) {
        this.ciname = ciname;
        this.tickets = tickets;
    }

    @Override
    public void run() {

        //没加同步 导致可用都成20
        synchronized (ciname){
            boolean flag = ciname.bookTickets(tickets);
            if (flag){
                System.out.println("购票成功"+Thread.currentThread().getName()+"-->"+tickets);
            }else {
                System.out.println("出票失败"+Thread.currentThread().getName()+"票数不够");
            }

        }


    }
}
